package com.family.exception;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.support.spring.FastJsonJsonView;
import com.family.model.result.ResultModel;
import com.family.model.result.StateCode;
import org.springframework.http.MediaType;
import org.springframework.web.servlet.HandlerExceptionResolver;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

public class GlobalItemsExceptionResolver implements HandlerExceptionResolver {
    @Override
    public ModelAndView resolveException(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) {
//        String message;
//        // 如果是自定义异常，给出具体的异常信息
//        if (ex instanceof ItemsException) {
//            message = ex.getMessage();
//        } else {
//            message = "服务器未知错误";
//        }

//        ModelAndView modelAndView = new ModelAndView();
//        modelAndView.addObject("errorMessage", message);
//        modelAndView.setViewName("test");


        ResultModel resultModel = new ResultModel();
        if (ex instanceof ItemsException) {
            resultModel.setStateCode(StateCode.PARAMS_ERROR);
            resultModel.setPrompt(ex.getMessage());
            resultModel.setErrorMessage(ex.getMessage());
        } else {
            resultModel.setStateCode(StateCode.OTHER_ERROR);
            resultModel.setErrorMessage(ex.getMessage());
            resultModel.setPrompt("服务器异常，请稍后");
        }
        response.setContentType(MediaType.APPLICATION_JSON_VALUE);
        response.setCharacterEncoding("UTF-8");
        response.setHeader("Cache-Control", "no-cache,must-revalidate");
        try {
            response.getWriter().write(JSON.toJSONString(resultModel));
        } catch (IOException e) {
            e.printStackTrace();
        }
        ex.printStackTrace();
        return new ModelAndView();
    }
}
